package com.ht.managermentserver.config;

import com.google.common.net.HttpHeaders;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * swagger 配置
 *
 * @author czy
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

  /**
   * 这里设置 swagger2 认证的安全上下文
   *
   * @author czy
   */
  private static SecurityContext securityContext() {
    return SecurityContext.builder()
        .securityReferences(defaultAuth())
        .forPaths(PathSelectors.any())
        .build();
  }

  private static List<SecurityReference> defaultAuth() {

    /** SecurityReference 参数 reference = ApiKey.name 或者 OAuthBuilder 中的name 表示引用 并插入 */
    return Collections.singletonList(new SecurityReference(HttpHeaders.AUTHORIZATION, scopes()));
  }

  /** 这里是写允许认证的scope */
  private static AuthorizationScope[] scopes() {
    return new AuthorizationScope[] {new AuthorizationScope("all", "All scope is trusted!")};
  }

  private static ApiInfo getApiInfo() {
    return new ApiInfoBuilder()
        .title("企业经营管理系统接口文档")
        .description("url 路径中 'api' 前缀为统一添加")
        .version("1.0")
        .build();
  }

  @Bean
  public Docket defaultrestControllerApiDocket() {

    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(getApiInfo())
        .groupName("默认分组")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.ht.managermentserver.controller"))
        .paths(PathSelectors.any())
        .build()
        .securitySchemes(getSecuritySchemes())
        .securityContexts(Collections.singletonList(securityContext()));
  }

  private List<SecurityScheme> getSecuritySchemes() {
    return Arrays.asList(apiKey());
  }

  /** 自定义 权限字段 */
  @Bean
  public ApiKey apiKey() {
    return new ApiKey(HttpHeaders.AUTHORIZATION, "authorization", "header");
  }
}
